# /bin/bash!
# 自动检查MD5值
# 自动重命名
# 自动比较分支信息
# 自动合成commit信息，文件名+时间+作者
# 自动提交
# 待完善：多分支提交时，自动切换分支并提交

md5v=$2

# input parameter check
if [[ $# != 4 ]]; then
	echo "usage: ./xxx.sh <file_name> <md5_value> <by_author> <branch_info>"
	exit 1
fi

# file md5sum check
# check_results=`md5sum $1 | grep "$md5v*"`
echo "info:----------------------------------------------------"
check_results=`md5sum $1`
echo "command(md5sum $1) results are: $check_results"

if [[ -z $md5v ]]; then
  echo "error:$md5v 字符串为空。"
  exit 1
fi

if [[ -z $check_results ]]; then
  echo "error:$check_results 字符串为空。"
  exit 1
fi
echo "info:----------------------------------------------------"
echo "md5 value compare"
if [[ "$check_results" =~ .*$md5v.* ]]; then
  echo "md5 value equal"
else
  echo "error:md5 value not equal,"
  echo $md5v
  echo $check_results
  exit 1
fi

# git 
echo "info:----------------------------------------------------"
branch_info=$4
remote_branch_info=`git status -uno | grep "origin/*"`
echo "remote_branch_info:$remote_branch_info"
#git status
git fetch
git pull

echo "info:----------------------------------------------------"
# check git branch
local_branch=`git branch | grep "* *"`
echo "local_branch:$local_branch"
if [[ "$local_branch" =~ .*$branch_info.* ]]; then
  echo "git branch info equal"
else
  echo "error:git branch info not equal,$branch_info To $local_branch"
  exit 1
fi

# file rename
infile=$1
outfile=
if [[ "$infile" =~ .*uboot.* ]];then
  echo "outfile:xynetuboot.img"
  outfile="xynetuboot.img"
elif [[ "$infile" =~ .*video.* ]];then
  echo "outfile:xyvideo.img"
  outfile="xyvideo.img"
elif [[ "$infile" =~ .*net.* ]];then
  echo "outfile:xynet.img"
  outfile="xynet.img"
elif [[ "$infile" =~ .*bin.* ]];then
  echo "outfile:fw_h6_mcu_v5.bin"
  outfile="fw_h6_mcu_v5.bin"
else
  echo "error:file name error:%infile"
  exit 1
fi
echo "info:----------------------------------------------------"
echo "cp $infile $outfile"
mv $infile $outfile


# Splicing git commit
echo "info:----------------------------------------------------"
time=$(date "+%Y-%m-%d %H:%M:%S")
author=$3
commit="update $outfile on $time by $author"
echo "git commit:$commit"

if [[ -z $author ]]; then
  echo "error:$author 字符串为空。"
  exit 1
fi

echo "info:----------------------------------------------------"
git add $outfile
git status -uno
echo "info:----------------------------------------------------"
git commit -m "$commit"
git status -uno
echo "info:----------------------------------------------------"
git push
echo "info:git push $outfile to $local_branch succeed"